package edu.upc.fib.lamsandroid.server.web.controller;

import edu.upc.fib.lamsandroid.server.manager.UserManager;
import edu.upc.fib.lamsandroid.server.api.response.user.GroupsResponse;
import edu.upc.fib.lamsandroid.server.api.response.user.LoginResponse;
import edu.upc.fib.lamsandroid.server.api.response.user.LogoutResponse;
import edu.upc.fib.lamsandroid.server.api.response.user.OrganisationsResponse;
import edu.upc.fib.lamsandroid.server.api.model.User;
import edu.upc.fib.lamsandroid.server.web.SessionContainer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    @Autowired
    SessionContainer sessionContainer;

    @Autowired
    UserManager userManager;

    @RequestMapping(value = "/user/login", method = RequestMethod.POST)
    public @ResponseBody LoginResponse login(@RequestParam("username") String username,
                                             @RequestParam("password") String password) {

        User user = sessionContainer.getSessionUser();
        if(user != null) {
            return LoginResponse.IS_ALREADY_LOGGED;
        }

        user = new User();
        user.setUsername(username);
        user.setPassword(password);
        if(userManager.completeByCredentials(user)) {
            sessionContainer.setSessionUser(user);
            return LoginResponse.IS_SUCCESSFUL;
        }

        return LoginResponse.HAS_WRONG_CREDENTIALS;
    }

    @RequestMapping(value = "/user/logout")
    public @ResponseBody LogoutResponse logout() {
        sessionContainer.setSessionUser(null);
        return LogoutResponse.IS_SUCCESSFUL;
    }

    @RequestMapping(value = "/user/groups")
    public @ResponseBody GroupsResponse groups() {
        User user = sessionContainer.getSessionUser();

        if(user == null) {
            return GroupsResponse.INVALID_SESSION_STATE;
        }

        return new GroupsResponse(user.getGroups());
    }

    @RequestMapping(value = "/user/organisations")
    public @ResponseBody OrganisationsResponse organisations() {
        User user = sessionContainer.getSessionUser();

        if(user == null) {
            return OrganisationsResponse.INVALID_SESSION_STATE;
        }

        return new OrganisationsResponse(user.getOrganisations());
    }

}
